<!--
 * @version: v 1.0.0
 * @Github: https://github.com/GitHubGanKai
 * @Author: GitHubGanKai
 * @Date: 2020-12-27 20:41:48
 * @LastEditors: gankai
 * @LastEditTime: 2021-01-02 20:29:34
 * @FilePath: /jingyikeji/src/views/home/index.vue
-->
<template>
  <div class="home">
    <!-- <header class="home-header" :class="{ active: headerActive }">
      <div class="header-search">
        <svg-icon class="search-icon" icon-class="search"></svg-icon>
        <router-link tag="span" class="search-title" to="./search"
          >推荐搜索 关键词</router-link
        >
      </div>
      <svg-icon
        class="customer-service-icon"
        icon-class="customer-service"
      ></svg-icon>
    </header> -->
    <van-swipe
      class="swiper-carousel"
      lazy-render
      :autoplay="3000"
      :show-indicators="false"
    >
      <van-swipe-item v-for="(banner, index) in homeImgs" :key="index">
        <img
          class="lazy_img"
          @click="handleClick(banner.skuId)"
          :src="banner.image"
        />
      </van-swipe-item>
    </van-swipe>
    <div class="content-tabs">
      <van-tabs
        :swipe-threshold="5"
        title-inactive-color="#3a3a3a"
        title-active-color="#D8182D"
        background="transparent"
        v-model="active"
        animated
        :before-change="tabChange"
      >
        <van-tab
          v-for="(list, index) in tabArray"
          :title="list.describe"
          :name="list.type"
          :key="index"
        >
          <template #title>
            <div class="slot-title">
              <b class="tab-title">{{ list.title }}</b>
              <span class="tab-name">{{ list.name }}</span>
            </div>
          </template>

          <section class="goods-box search-wrap">
            <ul class="goods-content">
              <li v-for="(item, index) in productList" :key="index">
                <router-link
                  class="goods-img"
                  tag="div"
                  :to="'/classify/product?skuId=' + item.skuId"
                >
                  <img :src="item.image" />
                </router-link>
                <div class="goods-layout">
                  <div class="goods-title">{{ item.name }}</div>
                  <span class="goods-div">{{ item.desc }}</span>
                  <div class="goods-desc">
                    <span class="goods-price">
                      <span class="price">{{ item.price / 100 }}</span>
                      <span class="force-value">元</span>
                    </span>
                    <span class="add-icon" @click="addToCart($event, item)">
                      <svg-icon icon-class="add"></svg-icon>
                    </span>
                  </div>
                </div>
              </li>
            </ul>
          </section>
        </van-tab>
      </van-tabs>
    </div>
    <div class="ballWrap">
      <transition
        @before-enter="beforeEnter"
        @enter="enter"
        @afterEnter="afterEnter"
      >
        <div class="ball" v-if="show">
          <li class="inner">
            <span class="cubeic-add" @click="addToCart($event, item)">
              <svg-icon class="add-icon" icon-class="add"></svg-icon>
            </span>
          </li>
        </div>
      </transition>
    </div>
    <tabbar></tabbar>
  </div>
</template>

<script>
import { ref, reactive, onMounted, toRefs, getCurrentInstance } from "vue";
import { useStore } from "vuex";
import { useRouter, useRoute } from "vue-router";
import Tabbat from "@/components/tabbar";
import { getUrlKey } from "../../utils/util";
export default {
  name: "home",
  components: {
    Tabbat,
  },
  setup(props, context) {
    const app = getCurrentInstance().appContext.app;
    const ctx = app.config.globalProperties;

    const $store = useStore();
    // ctx.$store === $store  ==>true 其实是同一个对象！

    const $router = useRouter();
    const $route = useRoute(); // 可以拿到所有和路由相关的参数
    const active = ref("");
    const timeData = ref(36000000);
    const headerActive = ref(false);

    const state = reactive({
      homeImgs: [],
      tabArray: [],
      productList: [],
    });

    const ball = reactive({
      show: false,
      el: "",
    });

    ctx.$http.get("http://test.happymmall.com/home/homeData").then((res) => {
      const { images, tabList } = res;
      state.tabArray = tabList;
      state.homeImgs = [
        {
          image:
            "https://imgcps.jd.com/img-cubic/creative_server_cia_jdcloud/v2/2000366/100022610168/FocusFullshop/CkNqZnMvdDEvMjQ5MzMyLzE3Lzc5NzQvMjUzNjIwLzY2MmQ1MGE1RjNjNmQ0MzVmLzdjNTliMmQ3NWU0ZjVmMjkucG5nEgkzLXR5XzBfNTQwAjjui3pCHQoZ6ZuF6K-X5YWw6bub5aWX6KOFL-ekvOebkhABQhMKD-S8mOaDoOS6q-S4jeWBnBACQhAKDOeri-WNs-aKoui0rRAGQgoKBuWKm-iNkBAHWPjRv870Ag/cr/s/q.jpg",
          skuId: "MZ1004",
        },
        {
          image:
            "https://imgcps.jd.com/ling-cubic/ling4/lab/amZzL3QxLzE3MTI1My8xOC8xMjE2MS81NjI2My82MDRiNTE3MkU1N2I1MzkwOS8wMDU5MDI1Mzg5MjM5Y2Q4LnBuZw/5Lqs6YCJ5aW96LSn/5L2g5YC85b6X5oul5pyJ/1635184859609366530/cr/s/q.jpg",
          skuId: "JD1001",
        },
        {
          image:
            "https://img12.360buyimg.com/n1/jfs/t1/226674/2/1791/163702/6543457dFf590580e/5a158b97f9e7008d.jpg.avif",
          skuId: "CS1001",
        },
      ];
    });

    /**
     * 获取商品列表
     */
    const getProductList = (groupId) => {
      /**
       * 商品列表
       */
      const params = {
        groupId,
      };
      ctx.$http.post("/s_shop/product/productList", params).then((data) => {
        console.log("productList", data);
        state.productList = data;
      });
    };

    onMounted(() => {
      checkIsLogin();
      ctx.$eventBus.$emit("changeTag", 0);
      window.addEventListener("scroll", pageScroll);
      getProductList(1);
    });

    /**
     * 获取accessToken
     * @param {*} param0
     */
    const getTokenByCode = async (params) => {
      const result = await ctx.$http.post(
        "/s_shop/user/getTokenByCode",
        params
      );
      return result;
    };
    const checkIsLogin = async () => {
      // 判断是否需要授权
      const code = getUrlKey("code");
      const token = localStorage.getItem("token");
      if (!token) {
        if (code) {
          const res = await getTokenByCode({
            appId: "wx82666013e409a8e7",
            code,
          });
          if (res) {
            localStorage.setItem("token", res);
          }
        } else {
          console.log("暂未登录");
          // toLogin();
        }
      }
    };
    /**
     * 切换tab执行
     * @param {*} e
     */
    const tabChange = (e) => {
      const groupId = e + 1;
      getProductList(groupId);
      active.value = e;
      return true;
    };
    /**
     * 加到购物车
     * @param {*} event
     * @param {*} tag
     */
    const addToCart = async (event, tag) => {
      const params = {
        goodId: tag.skuId,
        number: 1,
      };
      await ctx.$http.post("/s_shop/shopping_cart/setShoppingCart", params);

      $store.commit("cart/addToCart", tag);
      ball.show = true;
      ball.el = event.target;
    };

    /**
     * 页面进入前
     * @param {*} el
     */
    const beforeEnter = (el) => {
      const dom = ball.el;
      const rect = dom.getBoundingClientRect();
      const x = rect.left - window.innerWidth * 0.6;
      const y = -(window.innerHeight - rect.top);
      el.style.display = "block";
      el.style.transform = `translate3d(0,${y}px,0)`;
      const inner = el.querySelector(".inner");
      inner.style.transform = `translate3d(${x}px,0,0)`;
    };

    const enter = (el, done) => {
      document.body.offsetHeight;
      el.style.transform = "translate3d(0,0,0)";
      const inner = el.querySelector(".inner");
      inner.style.transform = "translate3d(0,0,0)";
      el.addEventListener("transitionend", done);
    };

    const afterEnter = (el) => {
      ball.show = false;
      el.style.display = "none";
    };

    const handleClick = (skuId) => {
      $router.push("/classify/product?skuId=" + skuId);
    };

    const pageScroll = () => {
      const scrollTop =
        window.pageYOffset ||
        document.documentElement.scrollTop ||
        document.body.scrollTop;
      scrollTop > 100
        ? (headerActive.value = true)
        : (headerActive.value = false);
    };

    return {
      active,
      timeData,
      headerActive,
      ...toRefs(ball),
      ...toRefs(state),
      addToCart,
      beforeEnter,
      enter,
      afterEnter,
      handleClick,
      pageScroll,
      tabChange,
    };
  },
};
</script>

<style scoped lang="scss" src="./index.scss"></style>
